package com.coder.algorithm.offer_2;

import java.util.Arrays;

/**
 * 礼物的最大价值
 *
 * @author yuhushuan
 * @date 2020/6/27 15:06
 */
public class _47_1_MaxValueOfGifts {
    private static int getMaxValue_solution1(int[][] values, int rows, int cols) {
        if (values == null || rows <= 0 || cols <= 0) {
            return 0;
        }
        int[][] maxValues = new int[rows][cols];
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < cols; ++col) {
                int left = 0;
                int up = 0;

                if (row > 0) {
                    up = maxValues[row - 1][col];
                }
                if (col > 0) {
                    left = maxValues[row][col - 1];
                }
                maxValues[row][col] = Math.max(left, up) + values[row][col];
            }
        }
        return maxValues[rows - 1][cols - 1];
    }

    private static int getMaxValue_solution2(int[][] values, int rows, int cols) {
        if (values == null || rows <= 0 || cols <= 0) {
            return 0;
        }
        int[] maxValues = new int[cols];
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < cols; ++col) {
                int left = 0;
                int up = 0;

                if (row > 0) {
                    up = maxValues[col];
                }
                if (col > 0) {
                    left = maxValues[col - 1];
                }
                maxValues[col] = Math.max(left, up) + values[row][col];
            }
        }
        return maxValues[cols - 1];
    }


    public static void main(String[] args) {
        int[][] matrix;

        matrix = new int[][]{
                {1, 10, 3, 8},
                {12, 2, 9, 6},
                {5, 7, 4, 11},
                {3, 7, 16, 5}
        };

        print(matrix);

    }

    private static void print(int[][] matrix) {
        System.out.println("棋盘上格子的礼物价值：");
        printMatrix(matrix);

        if (matrix == null) {
            System.out.println("最大价值礼物总和："
                    + getMaxValue_solution1(matrix, 0, 0));
        } else {
            System.out.println("最大价值礼物总和："
                    + getMaxValue_solution1(matrix, matrix.length, matrix[0].length));
        }
        System.out.println();

    }

    private static void printMatrix(int[][] matrix) {
        if (matrix == null) {
            System.out.println("null");
            return;
        }
        for (int row = 0; row < matrix.length; ++row) {
            System.out.println(Arrays.toString(matrix[row]));
        }
    }

}
